package org.yong.springbootcmd.web.ws;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yong.springbootcmd.config.SpringUtil;
import org.yong.springbootcmd.model.vo.WsProtocol;
import org.yong.springbootcmd.service.WsProtocolService;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

@Component
@ServerEndpoint("/ws")
@Slf4j
public class WebSocketServer {

    private WsProtocolService protocolService = SpringUtil.getBean(WsProtocolService.class);

    // 会话
    private Session session;

    /**
     * 发送数据
     *
     * @param wp 协议数据
     */
    public static void sendMsg(WsProtocol wp) {
        DB.sessions.keySet().forEach(k -> sendMsg(k, wp));
    }

    /**
     * 发送数据
     *
     * @param id 会话ID
     * @param wp 协议数据
     */
    public static void sendMsg(String id, WsProtocol wp) {
        if (DB.sessions.containsKey(id)) {
            String s = JSON.toJSONString(wp);
            DB.sessions.get(id).session.getAsyncRemote().sendText(s);
        }
    }

    @OnOpen
    public void clientConnected(Session session) {
        DB.increaseConnectedClientNum();
        this.session = session;
        String id = session.getId();
        DB.sessions.put(id, this);
        sendMsg(id, WsProtocol.cmd("连接成功"));
    }

    @OnMessage
    public void receiveMessage(String message) {
        WsProtocol wp = JSON.parseObject(message, WsProtocol.class);
        WsProtocol ret = protocolService.handle(wp);
        sendMsg(this.session.getId(), ret);
    }

    @OnError
    public void onError(Throwable error) {
        log.warn(error.getMessage(), error);
    }

    @OnClose
    public void onClose() {
        DB.decreaseConnectedClientNum();
        DB.sessions.remove(this.session.getId());
    }

}